package com.echo.servlet.ArticleServlet;

import com.echo.entity.Article;
import com.echo.entity.User;
import com.echo.exception.ArticleException;
import com.echo.service.ArticleService;
import com.echo.service.CategoryService;
import com.echo.service.ArticleCategoryRelationService;
import com.echo.servlet.BaseServlet;
import com.echo.util.SessionUtils;
import com.echo.util.MarkdownUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Arrays;
import java.util.ArrayList;

/**
 * 发布文章Servlet：处理/publishArticle请求（POST）和/article-publish请求（GET）
 */
@WebServlet({"/publishArticle", "/article-publish"})
public class PublishArticleServlet extends BaseServlet { // 继承BaseServlet（封装重复逻辑）
    private final ArticleService articleService = new ArticleService();
    private final CategoryService categoryService = new CategoryService();
    private final ArticleCategoryRelationService relationService = new ArticleCategoryRelationService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("=== PublishArticleServlet doGet方法被调用 ===");
        System.out.println("请求URL: " + request.getRequestURL());
        System.out.println("请求URI: " + request.getRequestURI());
        
        // 校验登录状态（未登录重定向到登录页）
        User loginUser = SessionUtils.getCurrentUser(request);
        if (loginUser == null) {
            System.out.println("用户未登录，重定向到登录页");
            response.sendRedirect("/echo-network/login.html");
            return;
        }
        
        System.out.println("用户已登录，用户名为: " + loginUser.getUsername());
        
        // 加载所有分类
        System.out.println("=== 开始加载分类数据 ===");
        try {
            List<com.echo.entity.Category> categories = categoryService.getAllCategories();
            
            // 添加详细日志输出，查看分类数据情况
            System.out.println("=== 发布文章页面加载分类数据 ===");
            System.out.println("获取到的分类数量: " + categories.size());
            if (categories.isEmpty()) {
                System.out.println("警告：分类列表为空！数据库中可能没有分类数据。");
                System.out.println("请通过/admin/categoryAdd.html页面添加分类数据。");
            }
            for (com.echo.entity.Category category : categories) {
                System.out.println("分类ID: " + category.getCategoryId() + ", 分类名称: " + category.getCategoryName());
            }
            
            request.setAttribute("categories", categories);
            System.out.println("已将分类数据设置到request属性中");
        } catch (Exception e) {
            System.out.println("加载分类数据时发生异常: " + e.getMessage());
            e.printStackTrace();
            // 即使出错也设置一个空列表，避免页面渲染错误
            request.setAttribute("categories", new ArrayList<>());
        }
        
        // 转发到发布文章页面（使用BaseServlet的forward方法确保Thymeleaf正确渲染）
        forward(request, response, "/article-publish.html");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. 校验登录状态（未登录重定向到登录页）
        User loginUser = SessionUtils.getCurrentUser(request);
        if (loginUser == null) {
            response.sendRedirect("/echo-network/login.html");
            return;
        }

        // 2. 设置请求编码（防止中文乱码）
        request.setCharacterEncoding("UTF-8");

        // 3. 接收表单参数
        String title = request.getParameter("title");
        String content = request.getParameter("content");
        String[] categoryIds = request.getParameterValues("categoryIds");
        
        System.out.println("=== PublishArticleServlet 接收表单参数 ===");
        System.out.println("标题: " + title);
        System.out.println("内容: " + (content != null ? content.length() + " 字符" : null));
        System.out.println("分类ID数组: " + (categoryIds != null ? Arrays.toString(categoryIds) : null));
        System.out.println("分类ID数量: " + (categoryIds != null ? categoryIds.length : 0));

        try {
            // 4. 封装文章对象（作者ID从登录用户获取）
            Article article = new Article();
            article.setTitle(title);
            article.setContent(content);
            // 使用MarkdownUtils将Markdown内容转换为HTML
            String htmlContent = MarkdownUtils.markdownToHtml(content);
            article.setHtmlContent(htmlContent);
            
            // 获取作者用户名
            article.setAuthorUsername(loginUser.getUsername());
            System.out.println("使用登录用户名: " + loginUser.getUsername());

            // 5. 准备分类ID列表
            List<Integer> categoryIdList = new ArrayList<>();
            if (categoryIds != null && categoryIds.length > 0) {
                System.out.println("转换分类ID字符串数组为整数列表");
                for (String id : categoryIds) {
                    System.out.println("转换ID: " + id);
                    categoryIdList.add(Integer.parseInt(id));
                }
            }
            System.out.println("准备好的分类ID整数列表: " + categoryIdList);

            // 6. 调用Service发布文章，同时处理分类关系
            Integer articleId = articleService.publish(article, categoryIdList);

            // 7. 发布成功：设置成功提示并重定向到我的文章页
            request.getSession().setAttribute("successMsg", "文章发布成功！");
            response.sendRedirect("/echo-network/article-show");
        } catch (ArticleException e) {
            // 8. 业务异常（参数非法等）：回显错误信息到发布页
            request.setAttribute("errorMsg", e.getMessage());
            request.setAttribute("title", title); // 回显已输入的标题
            request.setAttribute("content", content); // 回显已输入的内容
            // 回显分类列表
            List<com.echo.entity.Category> categories = categoryService.getAllCategories();
            request.setAttribute("categories", categories);
            forward(request, response, "/article-publish.html");
        } catch (SQLException e) {
            // 9. 数据库异常：显示系统错误
            e.printStackTrace();
            request.setAttribute("errorMsg", "系统错误，文章发布失败");
            // 回显分类列表
            List<com.echo.entity.Category> categories = categoryService.getAllCategories();
            request.setAttribute("categories", categories);
            forward(request, response, "/article-publish.html");
        }
    }
}